<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
	<title>API接口调试工具</title>
	<link href="css/bootstrap.css" type="text/css" rel="stylesheet">
    <link href="css/jsonview.css" type="text/css" rel="stylesheet">
    <link href="css/autocomplete.css" type="text/css" rel="stylesheet">
    <style>

		/*Chrome滚动条样式*/
		::-webkit-scrollbar {
			width: 4px;
			height: 4px;

		}
		::-webkit-scrollbar-track {
			-webkit-box-shadow: inset 0 0 1px rgba(0,0,0,0.8);
			border-radius: 4px;
		}
		::-webkit-scrollbar-thumb {
			border-radius: 4px;
			-webkit-box-shadow: inset 0 0 1px rgba(0,0,0,.8);
			background-color: #dddddd;
		}

        #result {
			width: 100%;
			height: 480px;
            border: none;
			background: #f7f7f7;
            float: left;
			overflow-y: scroll;
			border-radius: 0;
			font-size: 12px;
			font-family: Menlo,Monaco,Consolas,"Courier New",monospace;
        }
        #input_method {
            border-radius: 0;
        }
		#env_menu {
			float: right;
		}
		#container_params {
			display: none;
			margin-top: 12px;
			margin-bottom: 12px;
			max-height: 320px;
			overflow-y: scroll;
		}
		#history_list {
			max-height: 700px;
			overflow-y: scroll;
		}
		#env_settings .input-group, #container_params .input-group {
			margin-bottom: 2px;
		}

		button {
			outline:none;
		}
		.input-group-btn .btn-default, .input-group-btn .btn-info, 
		.input-group-btn .btn-success, .input-group-btn .btn-primary {
            height: 34px;
        }
		.input-group-addon {
			background-color: #fff;
		}
		.modal {
			top: 20%;
		}
        .highlight {
            margin-top: -16px;
            margin-right: 0;
            margin-left: 0;
            border-width: 1px;
            border-bottom-right-radius: 4px;
            border-bottom-left-radius: 4px;
        }
        .box {
			float: left;
			width: 100%;
            background: #f5f5f5;
            border-top: 3px solid #d2d6de;
            margin-bottom: 20px;
        }
        .box.box-info, .box.box-history {
            border-top-color: #337ab7;
        }
		.box.box-history {
			background: #ffffff;
		}
		.history-item {
			padding: 8px;
			cursor: pointer;
			border-bottom: 1px solid #f2f2f2;
		}
		.history-item:hover {
			background: #f6f6f6;
		}
		.history-item-title {
			font-weight: bold;
		}
		.history-item-title, .history-item-url {
			width: 100%;
			color: #888888;
			word-wrap: break-word;
		}
        .box-header {
            color: #337ab7;
            display: block;
            padding: 10px;
			font-weight: bold;
            position: relative;
        }
        .box-params, .box-env {
            width: 90%;
            margin-left: 5%;
        }
        .box-params .form-control, .box-env .form-control {
            width: 50%;
        }
		.params-item .params-value, .env-item .env-item-url {
			border-left: none;
		}
		.modal-body {
			padding: 30px 15px;
		}
    </style>
</head>
<body>
<div class="container">
<div class="row" style="margin-top:80px;">
<div class="col-sm-3">
	<div style="width:100%;float:left;margin-top:74px;">
		<div class="box box-history">
			<div class="box-header"><span>历史记录</span>
				<button type="button" class="btn btn-primary btn-sm" style="margin-left:20px;" id="btn_reset_historydata">
					<span>重置历史记录</span>
				</button>
			</div>
			<div class="box-body" id="history_list"></div>
		</div>
	</div>
</div>
<div class="col-sm-8">
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div style="float:left;width:100%;">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">API接口调试工具</a>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li><a href="#about"></a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div style="float:left;width:100%;">
		<div style="float:right;margin-left:20px;">
			<button type="button" class="btn btn-primary" id="btn_settings"><span class="glyphicon glyphicon-cog"></span> 设置</button>
		</div>
        <div class="btn-group" id="env_menu">
            <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
                <span class="current-env"></span> <span class="caret"></span>
            </button>
            <ul class="dropdown-menu">
                <li><a href="#"></a></li>
            </ul>
        </div>
    </div>

    <div class="" style="width:100%;margin-top:40px;float:left;">
        <div class="box box-info">
            <div class="box-body">
                <div class="input-group" style="margin:8px;">
                    <span class="input-group-addon">Action</span>
                    <input type="text" class="form-control" id="input_method">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button" data-toggle="button" aria-pressed="false" id="btn_params">参数</button>
                        <button class="btn btn-primary" type="button" id="btn_go"> GO </button>
                    </span>
                </div>

				<div id="container_params">
					<div class="input-group box-params">
						<div class="params-item">
							<input type="text" class="form-control input-sm params-key" placeholder="key">
							<input type="text" class="form-control input-sm params-value" placeholder="value">
						</div>
						<span class="input-group-btn">
							<button class="btn btn-danger btn-sm" type="button">
								<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>
							</button>
						</span>
					</div>
				</div>
            </div>
        </div>
    </div>

    <div style="width:100%;margin-top:40px;float:left;">
        <div class="box box-info">
            <div class="box-header">
                <div class="btn-group" id="toolbar">
                    <button type="button" class="btn btn-default btn-sm active" data-toggle="button" aria-pressed="true" id="btn_formateddata">格式化</button>
                    <button type="button" class="btn btn-default btn-sm" data-toggle="button" aria-pressed="false" id="btn_rawdata">原始数据</button>
                </div>
            </div>
            <div class="box-body">
                <div id="result"></div>
            </div>
        </div>
    </div>
</div>
</div>
</div>
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/bootstrap.js"></script>
    <script type="text/javascript" src="js/autocomplete.js"></script>
    <script type="text/javascript" src="js/jsonview.js"></script>
    <script type="text/javascript" src="js/webstorage.js"></script>
	<script type="text/javascript" src="js/methods.js"></script>
	<script type="text/javascript" src="js/sampledata.js"></script>
	<script type="text/javascript">

		$(document).ready(function(){

			//console.info('API接口调试工具');

			var jsonFormatter = new JSONFormatter();
			var ApiTool = {};

			ApiTool.apiUrl = '';
			ApiTool.rawData = '';
			ApiTool.formatedData = '';

            //初始化设置面板
            init_settings_modal();
			//初始获取SESSID面板
			init_get_sessid_modal();
            //初始化设置
            init_settings();
			//初始化历史纪录(样例数据)
			if (!webStorage.get('history_data')) {
				init_history_data(sampleHistoryData);
			}
			//初始化历史记录
			init_history_list();

            $("#input_method").autocomplete({
				limit: 1000,
				visibleLimit: 1000,
				openOnFocus:true,
				autoselect:true,
                source:[apiListData]
            }).on('input', function(){
				var data = [];
				var key = $(this).val();
				var regex = new RegExp(key);
				var history = webStorage.get('history_data') || sampleHistoryData;

				if (key) {
					for (i=0; i<history.length; i++) {
						if (regex.test(history[i]['title'])) {
							data.push(history[i]);
						}
					}

					//更新历史记录列表
					init_history_list(data);
				}
			});

            $("#btn_params").click(function(){
                $("#container_params").toggle();
            });

            $("#tabpage").click(function(e) {
                e.preventDefault();
                $(this).tab('show');
            });

            //接口环境菜单选项
            $("#env_menu .dropdown-menu").find("a").click(function() {
                var envname = $(this).html();
				var settings = webStorage.get('env_settings') || sampleEnvSettings;

                if (settings) {
                    var len = settings.length;
                    for (var i=0; i<len; i++) {
                        if (envname == settings[i]['name']) {
							ApiTool.apiUrl = settings[i]['url'];
							break;
                        }
                    }
				}

				if(envname) {
                    $("#env_menu").find('.current-env').text(envname);
                }
            });

            $(document).on('click', '#container_params .box-params:last input', function(){
                var html = '';
                html += '<div class="input-group box-params">';
                html += '  <div class="params-item">';
                html += '    <input type="text" class="form-control input-sm params-key" placeholder="key">';
                html += '    <input type="text" class="form-control input-sm params-value" placeholder="value">';
                html += '  </div>';
                html += '  <span class="input-group-btn params-item-delete">';
                html += '    <button class="btn btn-danger btn-sm" type="button">';
				html += '      <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
				html += '    </button>';
                html += '  </span>';
                html += '</div>';

                $("#container_params").append(html);
            });

			$(document).on('click', '#container_params .params-value', function(){
                var parent = $(this).parent();
				var paramKey = parent.find(".params-key:eq(0)").val();

				if (paramKey == 'ssid') {
					$("#getSessidModal").modal('show');
				}
            });

            $(document).on('click', '#env_settings .env-item:last input', function(){
                var html = '';
                html += '<div class="input-group box-env">';
                html += '  <div class="env-item">';
                html += '    <input type="text" class="form-control input-sm env-item-name" placeholder="接口环境名称">';
                html += '    <input type="text" class="form-control input-sm env-item-url" placeholder="接口URL">';
                html += '  </div>';
                html += '  <span class="input-group-btn env-item-delete">';
                html += '    <button class="btn btn-danger btn-sm" type="button">';
				html += '      <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
				html += '    </button>';
                html += '  </span>';
                html += '</div>';

                $("#env_settings").append(html);
            });

			$(document).on('click', '#history_list .history-item', function(){
				var url = $(this).find(".history-item-url:eq(0)").text();
				var url_parts = parse_url(url);
				var action = '';
				var params = url_parts['params'] || [];
				var api_url = url_parts['api_url'] || '';

				for(var i=0; i < params.length; i++) {
					if (params[i]['key'] == 'action') {
						$("#input_method").val(params[i]['value']);
						break;
					}
				}

				var html = get_params_html(params);
				if (html) {
					$("#container_params").html(html);
					$("#container_params").show();
					$("#btn_params").addClass('active');
				}

				if (api_url) {
				    var settings = webStorage.get('env_settings') || sampleEnvSettings;

					if (settings) {
						var len = settings.length;
						for (var i=0; i<len; i++) {
							if (api_url == settings[i]['url']) {
								ApiTool.apiUrl = settings[i]['url'];
								$("#env_menu").find('.current-env').text(settings[i]['name']);
								break;
							}
						}
					}
				}
            });

            $(document).on('click', '#container_params .params-item-delete', function(){
                $(this).parent().remove();
            });

            $(document).on('click', '#settingsModal .env-item-delete', function(){
                $(this).parent().remove();
            });

            $("#btn_go").click(function(){
                var params = get_params_data();
				var apiMethod = $("#input_method").val();

				if (apiMethod) {
					params['action'] = apiMethod;
				} else {
					return;
				}

				if (ApiTool.apiUrl) {
					params['api_url'] = ApiTool.apiUrl;
				}

                //发送请求
                request('get.php', params, function(){
					var formated = $("#btn_formateddata").attr("aria-pressed");
					if (formated == "true") {
						$("#result").html(ApiTool.formatedData);
					} else {
						$("#result").html(ApiTool.rawData);
					}

					//加入到历史列表
					var temp = [];
					for (k in params) {
						if (k == 'api_url') {
							continue;
						}
						temp.push(k + '=' + params[k]);
					}

					var data = {};
					data['title'] = params['action'];
					data['url'] = temp.length ? ApiTool.apiUrl + '?' + temp.join('&') : ApiTool.apiUrl;
					add_to_history(data);
					if (data['title'] && data['url']) {
						var html = get_history_html(data);
						$("#history_list").prepend(html);
					}
					
                });
            });

			$("#btn_rawdata").click(function(){
				$("#result").html(ApiTool.rawData);
			});

			$("#btn_formateddata").click(function(){
				if (ApiTool.formatedData) {
					$("#result").html(ApiTool.formatedData);
				} else {
					$("#result").html(ApiTool.rawData);
				}
			});

			$("#btn_settings").click(function(){
                $("#settingsModal").modal('show');
            });

			$("#toolbar button").click(function(){
				$("#toolbar button").each(function(){
					$(this).removeClass('active');
					$(this).attr('aria-pressed', 'false');
				});
            });

			$("#btn_reset_historydata").click(function(){
                webStorage.remove('history_data');
				init_history_list();
            });

            $(document).on('click', '#btn_save_settings', function(){
                var data = [];
                var env_settings = $("#env_settings .env-item");

                env_settings.each(function(){
                    var item = {};
                    var eleEnvItem = $(this);
                    item.name = eleEnvItem.find(".env-item-name:eq(0)").val();
                    item.url = eleEnvItem.find(".env-item-url:eq(0)").val();
                    if (item.name != '' && item.url != '') {
                        data.push(item);
                    }
                });

                webStorage.set('env_settings', data);
                $("#settingsModal").modal('hide');
            });

			$(document).on('click', '#btn_get_sessid', function(){
                var mid = $("#user_mid").val();

				if (mid) {
					get_user_sessid(mid, function(data){
						if (data['result']) {
							$("#container_params .params-key").each(function(){
								var that = $(this);
								if (that.val() == 'ssid') {
									that.parent().find(".params-value").val(data['result']);
								}
							});
							$("#getSessidModal").modal('hide');
						}
					});
				}
            });

			function parse_url(url) {
				var result = {};
				var regex = /(.*)\?(.*)/i;

				if (url) {
					var parts = regex.exec(url);
					if (parts) {
						var params = [];
						result['api_url'] = parts[1] ? parts[1]:'';
						if (parts[2]) {
							var items = parts[2].split('&');
							for (var i=0; i<items.length; i++) {
								var item = {};
								var temp = items[i].split('=');
								item['key'] = temp[0];
								item['value'] = temp[1];
								params.push(item);
							}
						}
						result['params'] = params;
					}
				}

				return result;
			}

            function get_params_data() {
                var data = {};
                var params = $("#container_params .params-item");

                params.each(function(){
                    var eleParamsItem = $(this);
                    var key = eleParamsItem.find(".params-key:eq(0)").val();
                    var value = eleParamsItem.find(".params-value:eq(0)").val();

                    if (key != '') {
                        data[key] = value;
                    }
                });

                return data;
            }

			function init_settings_modal() {
                var html = '';
                html += '<div class="modal fade" id="settingsModal" tabindex="-1" role="dialog">';
                html += '  <div class="modal-dialog">';
                html += '    <div class="modal-content">';
                html += '      <div class="modal-header">';
                html += '        <button type="button" class="close" data-dismiss="modal">';
				html += '			<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>';
				html += '		 </button>';
                html += '        <h4 class="modal-title" id="settingsModalLabel">接口配置管理</h4>';
                html += '      </div>';
                html += '      <div class="modal-body" id="env_settings">';
				html += '		 <div class="input-group box-env">';
				html += '          <div class="env-item">';
				html += '            <input type="text" class="form-control input-sm env-item-name" placeholder="接口环境名称">';
				html += '            <input type="text" class="form-control input-sm env-item-url" placeholder="接口URL">';
				html += '          </div>';
				html += '          <span class="input-group-btn">';
				html += '    	     <button class="btn btn-danger btn-sm" type="button">';
				html += '      		   <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
				html += '    		 </button>';
				html += '          </span>';
				html += '        </div>';
				html += '      </div>';
                html += '      <div class="modal-footer">';
                html += '        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>';
                html += '        <button type="button" class="btn btn-primary" id="btn_save_settings">保存配置</button>';
                html += '      </div>';
                html += '    </div>';
                html += '  </div>';
                html += '</div>';

                $('body').append(html);
            }

            function init_get_sessid_modal() {
                var html = '';
                html += '<div class="modal fade" id="getSessidModal" tabindex="-1" role="dialog">';
                html += '  <div class="modal-dialog">';
                html += '    <div class="modal-content">';
                html += '      <div class="modal-header">';
                html += '        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
                html += '        <h4 class="modal-title" id="getSessidModalLabel">获取用户SESSID</h4>';
                html += '      </div>';
                html += '      <div class="modal-body">';
				html += '		 <div class="input-group" style="width:90%;margin-left:5%;">';
				html += '          <div class="">';
				html += '            <input type="text" class="form-control user-mid" placeholder="用户MID" id="user_mid">';
				html += '          </div>';
				html += '          <span class="input-group-btn">';
				html += '            <button class="btn btn-default" type="button" id="btn_get_sessid">获取SSID</button>';
				html += '          </span>';
				html += '        </div>';
				html += '	   </div>';
                html += '    </div>';
                html += '  </div>';
                html += '</div>';

                $('body').append(html);
            }

            function get_env_item_html(item) {
                var html = '';

                html += '<div class="input-group box-env">';
                html += '  <div class="env-item">';
                html += '    <input type="text" value="' + item.name + '" class="form-control input-sm env-item-name" placeholder="接口环境名称">';
                html += '    <input type="text" value="' + item.url + '" class="form-control input-sm env-item-url" placeholder="接口URL">';
                html += '  </div>';
                html += '  <span class="input-group-btn env-item-delete">';
                html += '    <button class="btn btn-danger btn-sm" type="button">';
				html += '      <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
				html += '    </button>';
                html += '  </span>';
                html += '</div>';

                return html;
            }

            function get_env_menu_html(item) {
                var html = '';

                html += '<li><a href="#">' + item.name + '</a></li>';

                return html;
            }

			function get_params_html(params) {
				var html = '';

				for (var i=0; i < params.length; i++) {
					html += '<div class="input-group box-params">';
					html += '  <div class="params-item">'
					html += '   <input type="text" class="form-control input-sm params-key" placeholder="key" value="' + params[i]['key'] + '">'
					html += '   <input type="text" class="form-control input-sm params-value" placeholder="value" value="' + params[i]['value'] + '">'
					html += '  </div>'
					html += '  <span class="input-group-btn params-item-delete">'
					html += '    <button class="btn btn-danger btn-sm" type="button">';
					html += '      <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
					html += '    </button>';
					html += '  </span>'
					html += '</div>';
				}

				return html;
			}

            function init_settings() {
                var env_settings_html = '';
                var env_menu_html = '';
                var current_env = '';
                var settings = webStorage.get('env_settings') || sampleEnvSettings;

                if (settings) {
                    var len = settings.length;
                    for (var i=0; i<len; i++) {
                        if (i == 0) {
                            current_env = settings[i]['name'];
							ApiTool.apiUrl = settings[i]['url'];
                        }
                        env_settings_html += get_env_item_html(settings[i]);
                        env_menu_html += get_env_menu_html(settings[i]);
                    }

                    $("#env_settings").html(env_settings_html);
                    $("#env_menu").find('.current-env').text(current_env);
                    $("#env_menu .dropdown-menu").html(env_menu_html);
                }
            }

			function init_history_data(data) {
				if (data) {
					webStorage.set('history_data', data);
				}

				return true;
			}

			function init_history_list(data) {
				var html = '';
				var history = data || webStorage.get('history_data') || sampleHistoryData;

				for (var i=0; i<history.length; i++) {
					html += get_history_html(history[i]);
				}

				$("#history_list").html(html);
			}

			function get_history_html(data) {
				var html = '';

				html += '<div class="history-item">';
				html += '  <div class="history-item-title">' + data['title'] + '</div>';
				html += '  <div class="history-item-url">' + data['url'].replace(/&/g, '&amp;') + '</div>';
				html += '</div>';

				return html;
			}

			function add_to_history(data) {
				if (data['title'] && data['url']) {
					var history = webStorage.get('history_data') || [];

					if (history) {
						history.unshift(data);
					} else {
						history.push(data);
					}

					return webStorage.set('history_data', history);
				}

				return false;
			}

			function get_user_sessid(mid, callback) {
				var url = ApiTool.apiUrl;
				var params = {};
				params['action'] = 'apitool.getUserSessId';
				params['mid'] = mid;

                $.get(url, params, function(data){
					callback(data);
                });
            }

            function request(url, params, callback) {
                $.get(url, params, function(data){
                        var output = data;
                        var cleanData = '';
                        var callbackData = '';
						var jsonRegex = /^\s*([\[\{].*[\}\]])\s*$/;
						var isJson = jsonRegex.test(data);

						ApiTool.rawData = data;

                        try {
							if (isJson) {
								var jsonObj = JSON.parse(data);
								if ( jsonObj ) {
									output = jsonFormatter.jsonToHTML(jsonObj, callbackData, url);
									ApiTool.formatedData = output;
								}
							}

                            //Callback
                            if (callback) {
                                callback(output);
                            }
                        } catch(e) {
                            console.log(e);
                        }
                });
            }
		});
	</script>
</body>
</html>
